package com.sgl.common.config;

import cn.hutool.http.HttpUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.rmi.ServerException;

/**
 * @author:xec
 * @date:2022/11/28 13:18
 **/
@Component
public class AuthorizationCodeServerInterceptor implements HandlerInterceptor {

    //应用授权码key不可更改
    @Value("${spring.application.name}")
    public String serverKey ;

    @Value("${communication.mode}")
    public String communication;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServerException {
        if (communication.equals("plc")) {
            try {
//            System.out.println(serverKey);
                String s = HttpUtil.get("127.0.0.1:12345/auth/isAvailable?serverKey=" + serverKey);
                if (Boolean.parseBoolean(s)) {
                    return true;
                } else {
                    throw new ServerException("授权码过期");
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new ServerException("授权码过期");
            }
        }
        return true;
    }
}